package com.thx.privilege.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thx.common.spring.BeanFactory;
import com.thx.common.struts2.CurdAction;
import com.thx.common.util.ComplexPropertyPreFilter;
import com.thx.common.web.ActionResult;
import com.thx.privilege.PriviHandle;
import com.thx.privilege.PriviHandleFactory;
import com.thx.privilege.PriviManagerFactory;
import com.thx.privilege.PriviObj;
import com.thx.privilege.model.PrivilegeType;
import com.thx.privilege.service.PrivilegeTypeManager;

/**
 * 
 * 建立日期 : 2014年5月8日  下午2:31:29<br>
 * 作者 : shiyan<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 */
@Namespace("/privilege")
@Action(value="privilege", results={
		@Result(name="tree", location = "/pages/system/privilege/tree.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" }) 
})
@Controller
@Scope("prototype")
public class PrivilegeAction  extends CurdAction<PrivilegeType> {

	private static final long serialVersionUID = -6630919718231013706L;
	
	private static final String AUTHTYPE_USER = "user";
	
	private static final String AUTHTYPE_ROLE = "role";
	
	private String authType;
	
	private String authObjId;//授权对象的id
	
	private String priviObjsJson;
	
	public void treeList(){
	   try {
			HashMap<String, PriviHandle> priviHandleMap = PriviHandleFactory.getHandles();
			List<TreeNode> nodeList = new ArrayList<TreeNode>();
			if(priviHandleMap.size()>0){
				Set<String> set =priviHandleMap.keySet();
				Iterator<String> it = set.iterator();
				while(it.hasNext()){
					String typeKey = it.next();
					PriviHandle handle = priviHandleMap.get(typeKey);
					List<PriviObj> pos =handle.getPriviObjects();
					ComplexPropertyPreFilter filter = new ComplexPropertyPreFilter();
					filter.setIncludes(new HashMap<Class<?>, String[]>() {
						private static final long serialVersionUID = -8411128674046835592L;
						{
							put(PriviObj.class, new String[] { "objId", "objName", "priviType", "children" });
						}
					});
					String treeNodes = com.alibaba.fastjson.JSON.toJSONString(pos,filter);
					List<PriviObj> list = new ArrayList<PriviObj>();
					if(authType.equals(AUTHTYPE_USER)){
						list = PriviManagerFactory.getpPriviManager().getUserPrivileges(authObjId, typeKey);
					}else if(authType.equals(AUTHTYPE_ROLE)){
						list = PriviManagerFactory.getpPriviManager().getRolePrivileges(authObjId, typeKey);
					}
					 List<String> objIds = new ArrayList<String>();
					for(PriviObj po : list){
						objIds.add(po.getObjId());
					}
					PrivilegeTypeManager privilegeTypeMgr = (PrivilegeTypeManager) BeanFactory.getBean("privilegeTypeManager");
				    nodeList.add(new TreeNode("priviTree"+nodeList.size(), treeNodes, objIds, privilegeTypeMgr.getByTypeKey(typeKey).getTypeName(), typeKey));
				}
				
			}
			writeJson( com.alibaba.fastjson.JSON.toJSONString(nodeList));
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public String reAuth() {
		try{
			com.alibaba.fastjson.JSONArray obj = (JSONArray) com.alibaba.fastjson.JSON.parse(priviObjsJson);
			Iterator<Object> it = obj.iterator();
			while (it.hasNext()){
				com.alibaba.fastjson.JSONObject o = (JSONObject) it.next();
				String priviType = o.getObject("typeKey", String.class);
				String[] objId =o.getObject("objIds", String[].class);
				if(authType.equals(AUTHTYPE_USER)){
					PriviManagerFactory.getpPriviManager().reAuthToUser(authObjId, objId, priviType);
				}else if(authType.equals(AUTHTYPE_ROLE)){
					PriviManagerFactory.getpPriviManager().reAuthToRole(authObjId, objId, priviType);
				}
			}
			setResult(ActionResult.SUCCESS, "授权成功！");
		}catch(Exception e){
			setResult(ActionResult.FAIL, "服务器异常！");
		}
		
		return JSON;
	}

	public String auth(){
		return "tree";
	}
	public String getAuthType() {
		return authType;
	}

	public void setAuthType(String authType) {
		this.authType = authType;
	}

	public String getAuthObjId() {
		return authObjId;
	}

	public void setAuthObjId(String authObjId) {
		this.authObjId = authObjId;
	}
	
	public String getPriviObjsJson() {
		return priviObjsJson;
	}

	public void setPriviObjsJson(String priviObjsJson) {
		this.priviObjsJson = priviObjsJson;
	}

	class TreeNode{
		private String treeId;
		private String datas;
		private List<String> checkDatas;
		private String typeName;
		private String typeKey;
		public String getTreeId() {
			return treeId;
		}
		public void setTreeId(String treeId) {
			this.treeId = treeId;
		}
		public String getDatas() {
			return datas;
		}
		public void setDatas(String datas) {
			this.datas = datas;
		}
		public List<String> getCheckDatas() {
			return checkDatas;
		}
		public void setCheckDatas(List<String> checkDatas) {
			this.checkDatas = checkDatas;
		}
		public String getTypeName() {
			return typeName;
		}
		public void setTypeName(String typeName) {
			this.typeName = typeName;
		}
		public String getTypeKey() {
			return typeKey;
		}
		public void setTypeKey(String typeKey) {
			this.typeKey = typeKey;
		}
		public TreeNode() {}
		public TreeNode(String treeId, String datas, List<String> checkDatas,
				String typeName, String typeKey) {
			this.treeId = treeId;
			this.datas = datas;
			this.checkDatas = checkDatas;
			this.typeName = typeName;
			this.typeKey = typeKey;
		}
		
		
	}
}
